import * as types from "./actionTypes02";
import { request } from "@apis/request";
import toast from "@utils/showToast";
import { addLocal, addSession } from "@depjs/storage";

const success = (bool) => ({ type: types.SUCCESS, data: bool });
const fail = (bool) => ({ type: types.FAIL, data: bool });
const createTask = (list) => ({ type: types.CREATE_TASK, data: list });
const taskList = (list) => ({ type: types.GET_TASK_LIST, data: list });
const taskDone = (list) => ({ type: types.SET_TASK_DONE, data: list });
const delTask = (list) => ({ type: types.DEL_ONE_TASK, data: list });
const clearAllTasks = (list) => ({ type: types.CLEAR_ALL_TASKS, data: list });
const notDoneData = (list) => ({ type: types.NOT_DONE_DATA, data: list });
const monthNotDone = (obj) => ({ type: types.MONTH_ONT_DONE, data: obj });
const getFestivalList = (list) => ({
    type: types.GET_FESTIVAL_LIST,
    data: list,
});
const addFestival = (addData) => ({
    type: types.ADD_ONE_FESTIVAL,
    data: addData,
});
const removeFestival = (createTime) => ({
    type: types.REMOVE_ONE_FESTIVAL,
    data: createTime,
});
const getFestival = (createTime) => ({
    type: types.GET_ONE_FESTIVAL,
    data: createTime,
});
const clearFestival = (list) => ({
    type: types.CLEAR_ALL_FESTIVAL,
    data: list,
});
const reEditFestival = (obj) => ({ type: types.REEDIT_FESTIVAL, data: obj });
const getPrevious = (list) => ({ type: types.GET_PREVIOUS, data: list });

// 注册
export const registerAction = (userName, password, sex, from, headImg) => {
    return async (dispatch) => {
        const res = await request(
            "/register",
            { userName, password, sex, headImg },
            "post"
        );

        if (res.code === "0000") {
            toast.success("注册成功");

            dispatch(success(true));

            addSession(res.data);

            window.location.href = from;
        } else {
            dispatch(fail(false));
            toast.fail(res.message);
        }
    };
};

// 登录
export const loginAction = (userName, password, from, isChecked) => {
    return async (dispatch) => {
        const res = await request("/login", { userName, password }, "post");

        if (res.code === "0000") {
            toast.success("登录成功");

            dispatch(success(true));

            isChecked ? addLocal(res.data) : addSession(res.data);

            window.location.href = from;
        } else {
            dispatch(fail(false));
            toast.fail(res.message);
        }
    };
};

// 创建任务
export const createTaskAction = (taskDate, title, content, preDate) => {
    return async (dispatch) => {
        const res = await request(
            "/createtask",
            { taskDate, title, content, preDate },
            "post"
        );

        if (res.code === "0000") {
            toast.success("创建成功!");
            dispatch(createTask(res.data));
        } else {
            dispatch(createTask([]));
            toast.fail(res.message);
        }
    };
};

// 获取指定日期任务列表
export const getTaskListAction = (taskDate) => {
    return async (dispatch) => {
        const res = await request("/theDayTaskList", { taskDate });

        if (res.code === "0000") {
            dispatch(taskList(res.data));
        } else {
            toast.fail(res.message);
            dispatch(taskList([]));
        }
    };
};

// 设置任务已完成
export const setTaskDoneAction = (taskId) => {
    return async (dispatch) => {
        const res = await request("/setDone", { taskId }, "post");

        if (res.code === "0000") {
            toast.success("设置成功");
            dispatch(taskDone(res.data));
        } else {
            toast.fail(res.message);
            dispatch(taskDone([]));
        }
    };
};

// 删除一个任务
export const delOneTaskAction = (taskId) => {
    return async (dispatch) => {
        const res = await request("/delOneTask", { taskId }, "post");

        if (res.code === "0000") {
            toast.fail("删除成功！");
            dispatch(delTask(res.data));
        } else {
            toast.fail(res.message);
            dispatch(delTask([]));
        }
    };
};

// 清空指定日期所有任务
export const clearAllTasksAction = (dayId) => {
    return async (dispatch) => {
        const res = await request("/clearAllTasks", { dayId }, "post");

        if (res.code === "0000") {
            toast.fail("任务已清空！");
            dispatch(clearAllTasks(res.data));
        } else {
            toast.fail(res.message);
        }
    };
};

// 任务指示牌数据
export const notDoneDataAction = () => {
    return async (dispatch) => {
        const res = await request("/notDoneList");

        if (res.code === "0000") {
            dispatch(notDoneData(res.data));
        } else {
            console.log(res.message);
        }
    };
};

// 每月未完成情况
export const monthNotDoneAction = (y, m) => {
    return async (dispatch) => {
        const res = await request("/everyDayAMonth", { y, m });

        if (res.code === "0000") {
            dispatch(monthNotDone(res.data));
        } else {
            console.log(res.message);
        }
    };
};

// 获取自定义节日列表
export const getFestivalListAction = () => {
    return async (dispatch) => {
        const res = await request("/getAllFestival");

        if (res.code === "0000") {
            dispatch(getFestivalList(res.data));
        } else {
            console.log(res.message);
        }
    };
};

// 添加自定义节日
export const addFestivalAction = (m, d, content, isRemind) => {
    return async (dispatch) => {
        const res = await request(
            "/addFestival",
            { m, d, content, isRemind },
            "post"
        );

        if (res.code === "0000") {
            dispatch(addFestival(res.data));
        } else {
            console.log(res.message);
        }
    };
};

// 删除自定义节日
export const removeFestivalAction = (createTime) => {
    return async (dispatch) => {
        const res = await request("/removeOneFestival", { createTime }, "post");

        if (res.code === "0000") {
            dispatch(removeFestival(res.data));
        } else {
            console.log(res.message);
        }
    };
};

// 获取某个自定义节日
export const getFestivalAction = (createTime) => {
    return async (dispatch) => {
        const res = await request("/queryOneFestival", { createTime });

        if (res.code === "0000") {
            dispatch(getFestival(res.data));
        } else {
            console.log(res.message);
        }
    };
};

// 清除所有自定义节日
export const clearAllFestivalAction = () => {
    return async (dispatch) => {
        const res = await request("/clearAllFestival", {}, "post");

        if (res.code === "0000") {
            dispatch(clearFestival(res.data));
        } else {
            console.log(res.message);
        }
    };
};

// 重新编辑节日
export const reEditFestivalAction = (createTime, m, d, content, isRemind) => {
    return async (dispatch) => {
        const res = await request(
            "/reEditFestival",
            { createTime, m, d, content, isRemind },
            "post"
        );

        if (res.code === "0000") {
            dispatch(reEditFestival(res.data));
        } else {
            console.log(res.message);
        }
    };
};

// 获取往期功能列表
export const getPreviousAction = () => {
    return async (dispatch) => {
        const res = await request("/previousList");
        if (res.code === "0000") {
            dispatch(getPrevious(res.data));
        }
    };
};

// 往期功能点赞
const addPreviousLike = (obj) => ({ type: types.ADD_PREVIOUS_LIKE, data: obj });
export const addPreviousLikeAction = (id) => {
    return async (dispatch) => {
        const res = await request("/addPreviosLike", { id }, "post");
        if (res.code === "0000") {
            dispatch(addPreviousLike(res.data));
            toast.success("点赞成功，谢谢您的喜爱~");
        } else {
            toast.fail(res.message);
        }
    };
};

// 往期功能取消点赞
const cutPreviousLike = (obj) => ({ type: types.CUT_PREVIOUS_LIKE, data: obj });
export const cutPreviousLikeAction = (id) => {
    return async (dispatch) => {
        const res = await request("/cutPreviousLike", { id }, "post");
        if (res.code === "0000") {
            dispatch(cutPreviousLike(res.data));
            toast.info("取消成功！");
        } else {
            toast.fail(res.message);
        }
    };
};

// 获取研发项目列表
const getDevItemList = (list) => ({
    type: types.GET_DEV_ITEM_LIST,
    data: list,
});
export const getDevItemListAction = () => {
    return async (dispatch) => {
        const res = await request("/devItemList");
        if (res.code === "0000") {
            dispatch(getDevItemList(res.data));
        } else {
            console.log(res.message);
        }
    };
};

// 获取留言榜数据
const getLeaveMessageRank = (obj) => ({
    type: types.GET_LEAVE_MESSAGE_RANK,
    data: obj,
});
export const getLeaveMessageRankAction = () => {
    return async (dispatch) => {
        const res = await request("/getLeaveMessageRank");
        if (res.code === "0000") {
            const obj = res.data;
            const list = [];
            for (let i = 1; i <= 100; i++) {
                list.push({ sort: i });
            }
            const totalRank = [
                ...obj.totalRank,
                ...list.slice(obj.totalRank.length, 100),
            ];
            // const myRank = obj.myRank.length > 0 ? obj.myRank : [{}];
            dispatch(getLeaveMessageRank({ totalRank, myRank: obj.myRank }));
        } else {
            console.log("error: ", res.message);
        }
    };
};

// 发布留言
const publishLeaveMessage = (obj) => ({
    type: types.PUBLISH_LEAVE_MESSAGE,
    data: obj,
});
export const publishLeaveMessageAction = (title, content, navigate) => {
    return async (dispatch) => {
        const res = await request(
            "/publishLeaveMessage",
            { title, content },
            "post"
        );
        if (res.code === "0000") {
            dispatch(publishLeaveMessage(res.data));
            toast.success("发布成功");
            navigate(`/messageBoard/${res.data.key}`, { replace: true });
        } else {
            toast.fail(res.message);
        }
    };
};

// 获取我的留言
const getMyLeaveMessage = (list) => ({
    type: types.GET_MY_LEAVE_MESSAGE,
    data: list,
});
export const getMyLeaveMessageAction = () => {
    return async (dispatch) => {
        const res = await request("/getMyLeaveMessage");
        if (res.code === "0000") {
            dispatch(getMyLeaveMessage(res.data));
        }
    };
};

// 获取所有留言
const getAllLeaveMessages = (list) => ({
    type: types.GET_ALL_LEAVE_MESSAGE,
    data: list,
});
export const getAllLeaveMessagesAction = () => {
    return async (dispatch) => {
        const res = await request("/getAllLeaveMessages");
        if (res.code === "0000") {
            dispatch(getAllLeaveMessages(res.data));
        }
    };
};

// 获取所有被采纳留言
const getAllAcceptLeaveMessage = (list) => ({
    type: types.GET_ALL_ACCEPT_LEAVE_MESSAGE,
    data: list,
});
export const getAllAcceptLeaveMessageAction = () => {
    return async (dispatch) => {
        const res = await request("/getAllAcceptLeaveMessage");
        if (res.code === "0000") {
            dispatch(getAllAcceptLeaveMessage(res.data));
        }
    };
};

// 获取某条留言
const getOneLeaveMessage = (obj) => ({
    type: types.GET_ONE_LEAVE_MESSAGE,
    data: obj,
});
export const getOneLeaveMessageAction = (id) => {
    return async (dispatch) => {
        const res = await request("/getOneLeaveMessage", { id });
        if (res.code === "0000") {
            dispatch(getOneLeaveMessage(res.data));
        }
    };
};

// 点赞留言
const addLikeLeaveMessage = (obj) => ({
    type: types.ADD_LIKE_LEAVE_MESSAGE,
    data: obj,
});
export const addLikeLeaveMessageAction = (id) => {
    return async (dispatch) => {
        const res = await request("/addLikeLeaveMessage", { id }, "post");
        if (res.code === "0000") {
            dispatch(addLikeLeaveMessage(res.data));
        } else {
            toast.fail(res.message);
        }
    };
};

// 取消点赞留言
const cutLikeLeaveMessage = (obj) => ({
    type: types.CUT_LIKE_LEAVE_MESSAGE,
    data: obj,
});
export const cutLikeLeaveMessageAction = (id) => {
    return async (dispatch) => {
        const res = await request("/cutLikeLeaveMessage", { id }, "post");
        if (res.code === "0000") {
            dispatch(cutLikeLeaveMessage(res.data));
        } else {
            toast.fail(res.message);
        }
    };
};

// 删除某条留言
const deleteOneLeaveMessage = (obj) => ({
    type: types.DELETE_ONE_LEAVE_MESSAGE,
    data: obj,
});
export const deleteOneLeaveMessageAction = (id, navigate) => {
    return async (dispatch) => {
        const res = await request("/deleteOneLeaveMessage", { id }, "post");
        if (res.code === "0000") {
            dispatch(deleteOneLeaveMessage(res.data));
            navigate("/messageBoard/my-message", { replace: true });
            toast.success("删除成功");
        } else {
            toast.fail(res.message);
        }
    };
};

// 修改留言
const reviseLeaveMessage = (obj) => ({
    type: types.REVISE_LEAVE_MESSAGE,
    data: obj,
});
export const reviseLeaveMessageAction = (id, title, content, navigate) => {
    return async (dispatch) => {
        const res = await request(
            "/reviseLeaveMessage",
            { id, title, content },
            "post"
        );
        if (res.code === "0000") {
            dispatch(reviseLeaveMessage(res.data));
            toast.success("修改成功");
            navigate(`/messageBoard/${id}`, { replace: true });
        } else {
            toast.fail(res.message);
        }
    };
};

// 控制webchat上的一些同步状态切换
// 是否在搜索状态
export const isInSearch = (bool) => ({ type: types.IS_IN_SEARCH, data: bool });
// 添加朋友时，输入的搜索内容
export const addSearchValue = (str) => ({
    type: types.ADD_SEARCH_VALUE,
    data: str,
});
// 在右侧聊天栏头部显示的当前选择项的名称
export const selectItemNameShowChatHead = (str) => ({
    type: types.SELECT_ITEM_NAME_SHOW_CHAT_HEAD,
    data: str,
});
// 选择的表情包信息
export const selectEmojiInfo = (obj) => ({
    type: types.EMOJI_SELECT_INFO,
    data: obj,
});
// 记录编辑区光标位置
export const recordCurrentRange = (data) => ({
    type: types.RECORD_CURRENT_RANGE,
    data,
});

/**申请好友列表 */
const applyFriendsList = (list) => ({
    type: types.APPLY_FRIENDS_LIST,
    data: list,
});
export const applyFriendsListAction = () => {
    return async (dispatch) => {
        const res = await request("/chat/applyMeFriends");
        if (res.code === "0000") {
            dispatch(applyFriendsList(res.data));
        } else {
            console.log(res.message);
        }
    };
};

/**申请添加好友 */
const applyAddFriend = (bool) => ({ type: types.APPLY_ADD_FRIEND, data: bool });
export const applyAddFriendAction = (friend, applyWords, byname) => {
    return async (dispatch) => {
        const res = await request(
            "/chat/addFriend",
            { friend, applyWords, byname },
            "post"
        );
        if (res.code === "0000") {
            dispatch(applyAddFriend(res.data));
            toast.success("已发送添加好友申请~");
        } else {
            toast.fail(res.message);
        }
    };
};

// 是否打开了添加好友界面
export const isShowAddFriendBounced = (bool) => ({
    type: types.IS_SHOW_ADD_FRIEND_BOUNCED,
    data: bool,
});

// 获取好友列表
const friendsList = (arr) => ({ type: types.FRIENDS_LIST, data: arr });
export const getFrinedsListAction = () => {
    return async (dispatch) => {
        const res = await request("/chat/myFriendsList");
        if (res.code === "0000") {
            dispatch(friendsList(res.data));
        }
    };
};

// 自动添加自己为好友
const selfFriend = (obj) => ({ type: types.ADD_SELF_FRINED, data: obj });
export const addSelfFrinedAction = () => {
    return async (dispatch) => {
        const res = await request("/chat/addSelfFriend");
        if (res.code === "0000") {
            dispatch(selfFriend(res.data));
        }
    };
};

// 添加好友
export const addFriendAction = (obj) => ({ type: types.ADD_FRIEND, data: obj });
// 更新好友栏中聊天信息的最后一条消息内容
export const updateLastChatMessageAction = (obj) => ({
    type: types.UPDATE_LAST_CHAT_MESSAGE,
    data: obj,
});

// 设置某个用户发来的消息为已读
const setChaterMessageRead = (arr) => ({
    type: types.SET_CHAT_MESSAGE_READ,
    data: arr,
});
export const setChaterMessageReadAction = (chater) => {
    return async (dispatch) => {
        const res = await request(
            "/chat/setChaterMessageRead",
            { chater },
            "post"
        );
        if (res.code === "0000") {
            dispatch(setChaterMessageRead(res.data));
        }
    };
};

// 获取和某人的聊天列表
const getChatMessageList = (arr) => ({
    type: types.GET_CHAT_MESSAGE_LIST,
    data: arr,
});
export const getChatMessageListAction = (chater) => {
    return async (dispatch) => {
        const res = await request("/chat/getChatMsgWithFriend", { chater });
        if (res.code === "0000") {
            dispatch(getChatMessageList(res.data));
        }
    };
};

// 接收到新消息后，同步更新消息列表
export const updateNewMessageAction = (arr) => ({
    type: types.UPDATE_NEW_MESSAGE,
    data: arr,
});

// 删除某条消息
const deleteTheChatMessage = (arr) => ({
    type: types.DELETE_THE_CHAT_MESSAGE,
    data: arr,
});
export const deleteTheChatMessageAction = (messageId, chater) => {
    return async (dispatch) => {
        const res = await request(
            "/chat/deleteTheMessage",
            { messageId, chater },
            "post"
        );
        if (res.code === "0000") {
            toast.success("删除成功");
            dispatch(deleteTheChatMessage(res.data));
        }
    };
};

// friend item 给friend main同步传递数据（子传父）
export const friendItemToMainDataAction = (obj) => ({
    type: types.FRIEND_ITEM_TO_MAIN_DATA,
    data: obj,
});
// 是否显示修改备注名称的卡片
export const showMotifyBynameCardAction = (bool) => ({
    type: types.IS_SHOW_MOTIFY_BYNAME_CARD,
    data: bool,
});

// 修改好友备注名称
const motifyChaterByname = (arr) => ({
    type: types.MOTIFY_CHATER_BYNAME,
    data: arr,
});
export const motifyChaterBynameAction = (chater, newName, currentId) => {
    return async (dispatch) => {
        const res = await request(
            "/chat/motifyChaterByname",
            { chater, newName },
            "post"
        );
        if (res.code === "0000") {
            dispatch(motifyChaterByname(res.data));

            dispatch(showMotifyBynameCardAction(false));

            toast.success("修改成功");

            if (currentId === chater) {
                dispatch(selectItemNameShowChatHead(newName));
            }
        }
    };
};

// 消息免打扰 / 开启新消息提醒
const setIsBlockedChat = (obj) => ({
    type: types.SET_IS_BLOCKED_CHAT,
    data: obj,
});
export const setIsBlockedChatAction = (chater, isBlocked) => {
    return async (dispatch) => {
        const res = await request(
            "/chat/isSetChaterBlocked",
            { chater, isBlocked },
            "post"
        );
        if (res.code === "0000") {
            dispatch(setIsBlockedChat(res.data));
            toast.success("设置成功");
        }
    };
};
